package io.gitee.zhangbinhub.acp.cloud.serialnumber

import org.redisson.api.RedissonClient
import java.time.Duration

class RedisGenerateSerialNumber(private val redissonClient: RedissonClient) : GenerateSerialNumber {
    /**
     * 生成序列号
     * @param keyString 序列号键名称
     * @param expirationTime 过期时间（重新计数超时时间），单位毫秒，默认24小时
     */
    override fun getSerialNumber(keyString: String, expirationTime: Long): Long =
        redissonClient.getAtomicLong(keyString).let { rAtomicLong ->
            rAtomicLong.incrementAndGet().also {
                if (it == 1L) {
                    rAtomicLong.expire(Duration.ofMillis(expirationTime))
                }
            }
        }
}